package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * @author dcwu5
 * @date 2020-05-23
 * @description
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectAll(String statementId, Object... params) {
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> query = simpleExcutor.query(configuration, mappedStatement, params);
        return (List<E>) query;
    }

    @Override
    public <T> T selectOne(String statement, Object... params) {
        List<Object> objects = selectAll(statement, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或多个");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                Type genericReturnType = method.getGenericReturnType();
                if ("update".equals(methodName) || "insert".equals(methodName) || "delete".equals(methodName)){
                    return update(statementId, args);
                }
                if (genericReturnType instanceof ParameterizedType) {
                    List<Object> objectList = selectAll(statementId, args);
                    return objectList;
                }
                Object one = selectOne(statementId, args);
                return one;
            }

        });

        return (T) proxyInstance;
    }

    @Override
    public int update(String statementId, Object... params) {
        SimpleExcutor simpleExcutor = new SimpleExcutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        return  simpleExcutor.update(configuration, mappedStatement, params);
    }


}
